<?php

namespace App\Http\Controllers\Admin\Service;

use App\Exports\CompensateExport;
use App\Exports\ProblemExport;
use App\Http\Controllers\Admin\Examine\Record;
use App\Http\Controllers\Controller;
use App\Http\Requests\service\CompensateRequest;
use App\Models\base\CurrencyModel;
use App\Models\examine\ConfigModel;
use App\Models\examine\RecordDetailModel;
use App\Models\examine\RecordModel;
use App\Models\OrderModel;
use App\Models\RecBillModel;
use App\Models\service\CompensateModel;
use App\Models\service\ProblemModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Compensate extends Controller
{
    use CompensateRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $take_order_sn = $request->input('take_order_sn', '');
        $status = $request->input('status', '');
        $is_record = $request->input('is_record', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');


        $query = CompensateModel::query()->with(['compensate_admin', 'actual_currency', 'currency',  'order', 'customer', 'take_order']);

        if($take_order_sn){
            $take_order_ids  = TakeOrderModel::where('sn', $take_order_sn)->pluck('id');
            $query = $query->whereIn('take_order_id', $take_order_ids);
        }

        if($status){
            $query = $query->where('status', $status);
        }

        if($is_record != ''){
            $query = $query->where('is_record', $is_record);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'customer_name' => $item->customer->name ?? '',
                'take_order_sn' => $item->take_order->sn ?? '',
                'amount' => $item->amount,
                'currency_symbol' => $item->currency ? $item->currency->symbol : '',
                'actual_amount' => $item->actual_amount,
                'actual_currency_symbol' => $item->actual_currency ? $item->actual_currency->symbol : '',
                'remarks' => $item->remarks,
                'compensate_remarks' => $item->compensate_remarks,
                'status' => $item->status,
                'status_text' => CompensateModel::STATUS[$item->status],
                'compensate_admin_user' => $item->compensate_admin ? $item->compensate_admin->name : '',
                'created_at' => $item->created_at->toDateTimeString(),
                'is_record' => $item->is_record,
                'number' => $item->number,
                'weight' => $item->weight,
                'flight_date' => $item->flight_date,
                'start_port_code' => $item->start_port_code,
                'arrive_port_code' => $item->arrive_port_code,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }


    /**
     * Notes:确认赔偿
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirm(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::confirm_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = CompensateModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $currency_find = CurrencyModel::find($params['actual_currency_id']);

        DB::beginTransaction();
        try {

            $model->actual_amount = $params['actual_amount'];
            $model->actual_currency_id = $params['actual_currency_id'];
            $model->status = 4;
            $model->compensate_remarks = $params['compensate_remarks'] ?? '';
            $model->compensate_time = date('Y-m-d H:i:s');
            $model->compensate_admin_id = $auth->id;
            $model->save();

            // $bill_find = RecBillModel::whereRaw("FIND_IN_SET(?, take_order_ids)", [$model->take_order_id])->first();
            // $bill_find->currency = $currency_find->short_name;
            // $bill_find->amount = round($currency_find->amount - $params['actual_amount'], 2);
            // $bill_find->comp_amount = round($currency_find->comp_amount + $params['actual_amount'], 2);
            // $bill_find->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:审核通过
     * User: xiangzi
     * Date: 2024/9/20
     * Time: 10:02
     * @return \Illuminate\Http\JsonResponse
     */
    public function pass(Request $request, $id)
    {
        $auth = $request->get('auth');

        $model = CompensateModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $record = RecordModel::find($model->examine_record_id);
        if(!$record){
            return $this->error('审核记录不存在');
        }

        $detail = RecordDetailModel::where('record_id', $model->examine_record_id)->where('admin_id', $auth->id)->first();

        if(!$detail){
            return $this->error('不在审核流程内');
        }

        DB::beginTransaction();
        try {
            $detail->status = 2;
            $detail->examine_time = date('Y-m-d H:i:s');
            $detail->save();

            switch ($record->examine_type) {
                case 1:
                    $find_next = RecordDetailModel::where('record_id', $detail->record_id)->where('is_examine', 0)->orderBy('sort')->first();
                    if($find_next){
                        $find_next->is_examine = 1;
                        $find_next->save();
                    }else{
                        $record->status = 2;
                        $record->save();
                        $model->status = 2;
                        $model->save();
                    }
                    break;
                case 2:
                    $record->status = 2;
                    $record->save();
                    $model->status = 2;
                    $model->save();
                    break;
                case 3:
                    $find_else = RecordDetailModel::where('record_id', $detail->record_id)->where('status', 1)->first();
                    if(!$find_else){
                        $record->status = 2;
                        $record->save();
                        $model->status = 2;
                        $model->save();
                    }
                    break;
                default:

            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:不通过
     * User: xiangzi
     * Date: 2024/9/20
     * Time: 10:06
     * @return \Illuminate\Http\JsonResponse
     */
    public function refuse(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $model = CompensateModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $record = RecordModel::find($model->examine_record_id);
        if(!$record){
            return $this->error('审核记录不存在');
        }

        $detail = RecordDetailModel::where('record_id', $model->examine_record_id)->where('admin_id', $auth->id)->first();

        if(!$detail){
            return $this->error('不在审核流程内');
        }

        DB::beginTransaction();
        try {
            $detail->status = 3;
            $detail->examine_time = date('Y-m-d H:i:s');
            $detail->examine_remarks = $params['reason'] ?? '';
            $detail->save();

            $record->status = 3;
            $record->reason = $params['reason'] ?? '';
            $record->save();

            $model->status = 3;
            $model->save();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:详情
     * User: xiangzi
     * Date: 2024/9/20
     * Time: 11:30
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request, $id){
        $model = CompensateModel::with(['compensate_admin', 'actual_currency', 'currency', 'customer', 'take_order'])->find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $record = RecordModel::find($model->examine_record_id);

        $order = OrderModel::with(['customer', 'take_order'])->find($model->order_id);

        $return = [
            'base_info' => [
                'customer_name' => $order->customer->name ?? '',
                'take_order_sn' => $order->take_order->sn ?? '',
                'created_at' => $model->created_at->toDateTimeString(),
                'amount' => $model->amount,
                'currency_symbol' => $model->currency ? $model->currency->symbol : '',
                'remarks' => $model->remarks,
                'letter_file' => $model->letter_file,
                'pod_file' => $model->pod_file,
                'lose_invoice' => $model->lose_invoice,
                'whole_invoice' => $model->whole_invoice,
                'lose_list' => $model->lose_list,
                'whole_list' => $model->whole_list,
                'status' => $model->status,
                'status_text' => CompensateModel::STATUS[$model->status],
                'is_record' => $model->is_record == 1 ? '已生成' : '待生成',
                'pic_file' => $model->pic_file ? json_decode($model->pic_file, true) : []
            ],

            'compensate_info' => [
                'actual_amount' => $model->actual_amount,
                'actual_currency_symbol' => $model->actual_currency ? $model->actual_currency->symbol : '',
                'compensate_remarks' => $model->compensate_remarks,
                'compensate_admin_user' => $model->compensate_admin ? $model->compensate_admin->name : '',
                'compensate_time' => $model->compensate_time,
            ]
        ];

        if($record){
            $return['examine_info'] = [
                'examine_type' => ConfigModel::EXAMINE_TYPE[$record->examine_type] ??  '',
                'reason' => $record->reason,
                'examine_list' => (new Record())->examine_info($model->examine_record_id)
            ];
        }else{
            $return['examine_info'] = [
                'examine_type' => '',
                'reason' => '',
                'examine_list' => []
            ];
        }
        return $this->success($return);
    }


    public function export(Request $request){
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = CompensateModel::query()->with(['order', 'customer', 'take_order']);
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'customer_name' => $item->customer->name ?? '',
                'take_order_sn' => $item->take_order->sn ?? '',
                'amount' => $item->amount,
                'actual_amount' => $item->actual_amount,
                'remarks' => $item->remarks,
                'compensate_remarks' => $item->compensate_remarks,
                'status' => CompensateModel::STATUS[$item->status] ?? '',
                'created_at' => $item->created_at->toDateTimeString(),
            ];
            return $res;
        });

        $file_name = '赔偿列表-'.date('Ymd').'.xlsx';
        return Excel::download(new CompensateExport($list), $file_name);
    }

    // 补充信息
    public function info(Request $request) {
        $id = intval($request->input('id', 0));
        $params = $request->all();

        $compensate = CompensateModel::find($id);

        if(!$compensate){
            return $this->error('数据不存在');
        }

        $compensate->number = $params['number'] ??  0;
        $compensate->weight = $params['weight'] ?? 0;
        $compensate->save();

        return $this->success();
    }


}
